﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Controllers.SmallBatchTrial;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Services.Interface.OutsourcingProcessing;
using RndMaterialDisposalService.Services.Interface.SmallBatchTrial;
using RndMaterialDisposalService.Services.Interface.TemporaryDocument;
using RndMaterialDisposalService.Services.SmallBatchTrialService;
using Ganss.Excel;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace RndMaterialDisposalService.Controllers.SmallBatchTrial
{
    /// <summary>
    /// 外协加工电子流
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class OutsourcingProcessingController : ControllerBase
    {
        private ILogger<OutsourcingProcessingController> logger;
        private readonly string ProcessFullName = "SmallBatchTrial\\OutsourcingProcessings";
        private IOutsourcingProcessingService ioutsourcingProcessingService;
        private IConfiguration configuration;
        private readonly string SaveFormDataUrl = "/api/WorkflowData/ApplicationData";
        private readonly string ProcessFolioUrl = "/api/WorkflowData/ApplicationNumber";

        public OutsourcingProcessingController(ILogger<OutsourcingProcessingController> _logger,
            IOutsourcingProcessingService _ioutsourcingProcessingService,
            IConfiguration _configuration)
        {
            logger = _logger;
            ioutsourcingProcessingService = _ioutsourcingProcessingService;
            configuration = _configuration;
        }

        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="procInstID">流程实例编号</param>
        /// <param name="applicationNumber"></param>
        /// <returns></returns>
        [HttpGet("GetFormData")]
        public async Task<IActionResult> GetFormData(string? procInstID, string? applicationNumber)
        {
            var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
            var result = new FormInfoResp();
            if (!string.IsNullOrWhiteSpace(procInstID))
            {
                var url = $"{CommonServiceHost}{SaveFormDataUrl}?procInstID={procInstID}";
                result = await HttpHelper.GetAsync<FormInfoResp>(url);
                result.ViewsStatus = "Approval";
                return Ok(result);
            }

            var formDataModel = new OutsourcingProcessingElectronFlowReq();
            var url2 = $"{CommonServiceHost}{ProcessFolioUrl}?workflowCode={ProcessFullName}";
            var appNumber = await HttpHelper.GetAsync<string>(url2);
            result.ApplicationNumber = appNumber;
            result.ViewsStatus = "Start";
            result.FormData = JsonConvert.SerializeObject(formDataModel);
            return Ok(result);
        }

        /// <summary>
        /// 获取主流程填写环节数据
        /// </summary>
        /// <param name="ProcInstID"></param>
        /// <returns></returns>
        [HttpGet("TheMainFlowFormData")]
        public async Task<IActionResult> TheMainFlowFormData(string procInstID) 
        {
            var item = await ioutsourcingProcessingService.TheMainFlowFormData(procInstID);
            return Ok(item);
;        }

        /// <summary>
        /// 新增报表数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("SavaOutsourcingProcessingReportFormData")]
        public async Task<IActionResult> SavaOutsourcingProcessingReportFormData(OutsourcingProcessingBusinessDataModel input)
        {
            int count = 0;
            string _ProcInstId = input.ProcInstId ?? "0";
            try
            {
                if (input != null)
                {
                    input.SysId = Guid.NewGuid();
                    count = await ioutsourcingProcessingService.AddOutsourcingProcessingBusinessData(input);
                }
                logger.LogInformation($"新增报表数据（外协加工电子流）,流程实例号：{_ProcInstId},数量：{count},时间：{DateTime.Now}");
                return Ok(count);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"新增报表数据（外协加工电子流）,流程实例号：{_ProcInstId},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                throw;
            }
        }

        /// <summary>
        /// 返回外协加工电子流报表主数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("OutsourcingProcessingReportFormData")]
        [PageList]
        public IActionResult OutsourcingProcessingReportFormData(OutsourcingProcessingReportConditionModel input)
        {
            var list = ioutsourcingProcessingService.GetOutsourcingProcessingReportFormPageList(input);
            int count = ioutsourcingProcessingService.GetOutsourcingProcessingReportFormData(input).Count();

            var result = ApiResponsePageList<OutsourcingProcessingReportFormModel>.CreatePageListByResult(list, input.pageIndex, input.pageSize, count);

            return Ok(result);
        }

        /// <summary>
        /// 返回打印表单数据
        /// </summary>
        /// <param name="procInstID"></param>
        /// <returns></returns>
        [HttpGet("GetObtainPrintFormData")]
        public async Task<IActionResult> GetObtainPrintFormData(string procInstID)
        {
            var item = await ioutsourcingProcessingService.GetObtainPrintFormData(procInstID);
            return Ok(item);
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="relativePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet("DownloadFile")]
        [PageList]
        public async Task<IActionResult> DownloadFile(string relativePath, string fileName)
        {
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            var fileFullPath = $"{fileDir}\\{relativePath}";
            var stream = await System.IO.File.ReadAllBytesAsync(fileFullPath);
            return File(stream, "application/octet-stream", fileName);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("OutsourcingProcessingReportExport")]
        [PageList]
        public async Task<IActionResult> OutsourcingProcessingReportExport(OutsourcingProcessingReportConditionModel inputCondition)
        {
            inputCondition.pageIndex = 1;
            inputCondition.pageSize = 65535;
            var list = ioutsourcingProcessingService.GetOutsourcingProcessingReportFormData(inputCondition);
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            if (!System.IO.Directory.Exists($"{fileDir}\\Report"))
            {
                Directory.CreateDirectory($"{fileDir}\\Report");
            }
            var filePath = $"Report\\过程跟踪表外协加工电子流{Guid.NewGuid().ToString("N")}.xlsx";
            await new ExcelMapper().SaveAsync($"{fileDir}\\{filePath}", list);
            return Ok(filePath);
        }
    }
}
